import datetime

from flask import request, current_app
from flask_mail import Message
from flask_restful import abort

from main.settings import celery
from main.apis.api_constant import USER
from main.apis.utils import get_ordinary_user
from main.ext import mail, cache

from main.settings import SERVER_HOST


@celery.task
def send_mail(email: str = None, token: str = None):
    if email and token:
        app = current_app._get_current_object()
        url = f'{SERVER_HOST}user/?action=verify&token={token}'
        msg = Message(subject='验证您的邮箱', recipients=[email, ])
        msg.html = f'''
        <span>点击下面的链接验证您的邮箱：</span>
        <br>
        <a href={url}>点我验证</a>
        <p>如果上面的链接无法点击，请复制下面的链接到浏览器中打开：</p>
        <p>{url}</p>
        <br><span>(链接有效期为5分钟，只能访问一次)</span>
        '''
        with app.app_context():
            mail.send(msg)
        return True
    else:
        return False



def _verify():
    token = request.args.get('token')
    if not token:
        abort(401, error='未登录')
    if not token.startswith(USER):
        abort(401, error='已登录的用户可能不是普通用户，或者您尚未登录。')
    user_id = cache.get(token)
    if not user_id:
        abort(401, error='此操作需要登录。如果您之前已登录，可能是登录过期，请重新登录。')
    user = get_ordinary_user(user_id)
    if not user:
        abort(401, error='您的账户状态异常，请联系管理员')
    # 如果登录，则将用户和token传到跨域全局变量g中，用于权限认证
    # g.user = user
    # g.token = token


def ordinary_login_required(func):
    def wrapper(*args, **kwargs):
        _verify()
        return func(*args, **kwargs)

    return wrapper


def get_user_id():
    token = request.args.get('token')
    user_id = cache.get(token)
    return user_id


def get_now_time():
    now_raw = datetime.datetime.now()
    now = datetime.datetime.strftime(now_raw, '%Y-%m-%d %H:%M:%S')
    return now_raw, now
